package com.product.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.RocketMqConstant;
import com.product.dao.EquityDetailedDao;
import com.product.dao.ProductEquityDao;
import com.product.entity.EquityDetailed;
import com.product.entity.ProductEquity;
import com.common.Message.vo.OfflineMessage;
import com.product.rocketmq.RocketMqTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: Member_Perks_Store
 * @description: 权益商品定时轮询任务器
 * @author: 无恙
 * @create: 2024-06-18 16:23
 **/

@Component
public class ProductExpirationScheduler {

    @Autowired
    EquityDetailedDao equityDetailedDao;

    @Autowired
    ProductEquityDao productEquityDao;

    @Autowired
    @Qualifier("rocketMQ")
    private RocketMqTemplate rocketMqTemplate;


    /*
    * @author 范铁凝
    * @date 2024/6/18
    * 轮询数据库查询将在一天内过期的商品，凌晨一点
    * 30s一次，每次轮询获取此刻时间60s即将过期商品，将其下架
    */
    @Scheduled(fixedRate = 30000)
    public void productExpiration() {

        //获取60秒内要下架商品
        List<EquityDetailed> equityExpiringBetween = equityDetailedDao.
                findEquityExpiringBetween(LocalDateTime.now(), LocalDateTime.now().plusMinutes(60));
        //判断是否为空
        if (equityExpiringBetween.isEmpty()) {
            return;
        }

        //获取对应权益ID
        List<Long> collect = productEquityDao.selectList(new QueryWrapper<ProductEquity>()
                        .in("equity_detailed_id", equityExpiringBetween.stream()
                                .map(EquityDetailed::getId).toArray()))
                .stream().map(ProductEquity::getId).collect(Collectors.toList());
        //判断是否为空
        if (collect.isEmpty()) {
            return;
        }

        //生成消息
        collect.forEach(id -> rocketMqTemplate.send(RocketMqConstant.PRODUCT_OFFLINE_TOPIC,
                RocketMqConstant.PRODUCT_OFFLINE_TAG,new OfflineMessage(id),convertDelayTimeToLevel(60)));



    }
    private int convertDelayTimeToLevel(long delayTimeSeconds) {
        // 根据实际业务需要，将时间转换成对应的延迟级别
        // 这里仅作示例，实际需求中可能需要根据具体的延迟级别配置进行计算
        return (int) (delayTimeSeconds / 5); // 每5秒一个级别，实际需要根据延迟级别配置进行调整
    }

}
